//
//  ImageView+Extension.swift
//  RF_localRepo
//
//  Created by zrf on 2021/6/9.
//

import Foundation
import AVKit

public extension UIImageView{
    /// SwifterSwift: Make image view blurry.
    ///
    /// - Parameter style: UIBlurEffectStyle (default is .light).
    func blur(withStyle style: UIBlurEffect.Style = .light) {
        let blurEffect = UIBlurEffect(style: style)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = bounds
        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation
        addSubview(blurEffectView)
        clipsToBounds = true
    }

    /// SwifterSwift: Blurred version of an image view.
    ///
    /// - Parameter style: UIBlurEffectStyle (default is .light).
    /// - Returns: blurred version of self.
    func blurred(withStyle style: UIBlurEffect.Style = .light) -> UIImageView {
        let imgView = self
        imgView.blur(withStyle: style)
        return imgView
    }
    
    /// 获取视频中单张图片，用于视频封面
    /// - Parameters:
    ///   - url: 视频的URL对象
    ///   - atTime:第几秒视频图。默认视频第二张图片
    func setVideoImage(_ url: URL, atTime:Float64 = 1){
        DispatchQueue.global().async {
            let asset = AVURLAsset(url: url)
            let generator = AVAssetImageGenerator(asset: asset)
            generator.appliesPreferredTrackTransform = true
            generator.requestedTimeToleranceBefore = CMTime.zero
            generator.requestedTimeToleranceAfter = CMTime.zero
            let time = CMTimeMakeWithSeconds(atTime, preferredTimescale: 600)
            
            var actualTime: CMTime = CMTime.zero
            let imageRef = try? generator.copyCGImage(at: time, actualTime: &actualTime)
            if imageRef != nil {
                let img = UIImage(cgImage: imageRef!)
                
                DispatchQueue.main.async {
                    self.image = img
                }
            }
                
        }
    }
}



